import { Directive } from 'vue';
import vtTouchCom from '../v-drag/vtTouchCom.ts';

// 定义指令绑定值的接口
interface ResizeBinding {
    ujt: any;
    size?: any;
    scale?: any;
}

const vTmp: any = {};
const vPopresizezoom: Directive = {
    mounted(el: HTMLElement, binding: { value: ResizeBinding }) {
        const { fnPThrottle, vtTouchInit, vtTouchDown, vtTouchUp } = vtTouchCom(
            el,
            binding.value
        );
        vtTouchInit(el);
        const { ujt, size, scale } = binding.value;
        let elpos: any = { x: 0, y: 0 };
        let curscale: number;
        const maxArea: any = {
            width: ujt?.$global?.sys?.zoomwidth || 1920,
            height: ujt?.$global?.sys?.zoomheight || 1200,
        };
        const getScale = () => {
            return scale || ujt?.$global?.scale || 1;
        };
        let isResizing = false;
        let startX: number;
        let startY: number;
        let startWidth: number;
        let startHeight: number;
        let newSize: any = size || { w: 0, h: 0 };

        // 获取事件的 clientX 和 clientY
        const getClientPosition = (
            e: PointerEvent
        ): { clientX: number; clientY: number } => {
            return { clientX: e.clientX, clientY: e.clientY };
        };

        // 处理指针按下或触摸开始事件
        const handleDown = (e: PointerEvent) => {
            vtTouchDown(el);
            e.preventDefault(); // 阻止默认触摸行为
            curscale = getScale();
            isResizing = true;

            const { clientX, clientY } = getClientPosition(e);
            // 考虑滚动偏移，计算相对于视口的坐标
            startX = clientX - window.scrollX;
            startY = clientY - window.scrollY;
            startWidth = el.offsetWidth;
            startHeight = el.offsetHeight;

            // 获取元素当前的 transform 位置
            const dragAreaStyle: any = window.getComputedStyle(el);
            const transformArr = dragAreaStyle.transform?.split(', ');
            if (transformArr && transformArr.length > 2) {
                const valy = transformArr.pop().slice(0, -1);
                const valx = transformArr.pop();
                elpos = {
                    x: parseFloat(valx),
                    y: parseFloat(valy),
                };
            } else {
                elpos = { x: 0, y: 0 };
            }
            el.style.transform = `translate(${elpos.x}px,${elpos.y}px)`;

            if (e instanceof PointerEvent) {
                el.setPointerCapture(e.pointerId);
            }

            document.addEventListener(
                'pointermove',
                handleMove as EventListener
            );
            document.addEventListener('pointerup', handleUp as EventListener);
            document.addEventListener(
                'pointercancel',
                handleUp as EventListener
            );
        };

        // 处理指针移动或触摸移动事件
        const handleMove = (e: PointerEvent) => {
            if (!isResizing) return;

            fnPThrottle(() => {
                const { clientX, clientY } = getClientPosition(e);
                // 计算相对于视口的移动距离，并考虑缩放比例
                const dx = (clientX - window.scrollX - startX) / curscale;
                const dy = (clientY - window.scrollY - startY) / curscale;

                // 计算新的宽度和高度，确保不小于最小值
                newSize.w = Math.min(
                    Math.max(88, startWidth + dx),
                    maxArea.width - elpos.x
                );
                newSize.h = Math.min(
                    Math.max(58, startHeight + dy),
                    maxArea.height - elpos.y
                );

                // 更新元素的宽高
                el.style.width = newSize.w + 'px';
                el.style.height = newSize.h + 'px';
            });
        };

        // 处理指针松开或触摸结束事件
        const handleUp = (e: PointerEvent) => {
            vtTouchUp(el);
            if (
                e instanceof PointerEvent &&
                el.hasPointerCapture(e.pointerId)
            ) {
                el.releasePointerCapture(e.pointerId);
            }
            isResizing = false;
            document.removeEventListener(
                'pointermove',
                handleMove as EventListener
            );
            document.removeEventListener(
                'pointerup',
                handleUp as EventListener
            );
            document.removeEventListener(
                'pointercancel',
                handleUp as EventListener
            );
        };

        // 创建右下角调整大小的元素
        const resizeElement = document.createElement('div');
        resizeElement.classList.add('resize-bottom-right');

        el.appendChild(resizeElement);
        resizeElement.addEventListener(
            'pointerdown',
            handleDown as EventListener
        );

        // 挂载清理监听事件的方法
        vTmp.unmounted = () => {
            resizeElement.removeEventListener(
                'pointerdown',
                handleDown as EventListener
            );
            if (resizeElement) {
                resizeElement.remove();
            }
        };
    },
    unmounted(el: HTMLElement) {
        typeof vTmp?.unmounted == 'function' && vTmp.unmounted();
    },
};

export default vPopresizezoom;
